package org.charmsoft.generator;

import cn.hutool.core.io.FileUtil;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.charmsoft.dto.ClassesInWorkbook;
import org.charmsoft.error.ReturnCode;
import org.charmsoft.error.StatusCode;
import org.charmsoft.files.DefaultFreemarkerLoader;
import org.charmsoft.files.FreemarkerLoader;
import org.charmsoft.utils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ Author: Allen J L Chen
 * This Class is to
 * 9/4/2025
 **/
public class SQLGenerator implements Generator{

    private static final Logger LOGGER = LoggerFactory.getLogger(SQLGenerator.class);

    private static Path path = Paths.get("");

    private ClassesInWorkbook classesInWorkbook;

    public SQLGenerator(ClassesInWorkbook classesInWorkbook) {
        this.classesInWorkbook = classesInWorkbook;
    }

    @Override
    public StatusCode generate() {
       return generate(classesInWorkbook);
    }

    public synchronized StatusCode generate(ClassesInWorkbook classesInWorkbook) {
        FreemarkerLoader freemarkerLoader = new DefaultFreemarkerLoader();
        Template template = freemarkerLoader.loadTemplate(PropertyUtils.props.getProperty("SQL"));
        StatusCode statusCode = new StatusCode();
        String sPath = path.toAbsolutePath().toString()+ "/output/"+ classesInWorkbook.getProjectName()+ "/";
        if(!FileUtil.isDirectory(sPath)) {
            FileUtil.mkdir(sPath);
        }
        try{
			StringWriter stringWriter = new StringWriter();
            template.process(classesInWorkbook, stringWriter);
            stringWriter.flush();
            FileOutputStream fos = new FileOutputStream(sPath + classesInWorkbook.getWorkBookName()+".sql");
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            BufferedWriter bfw = new BufferedWriter(osw);
            template.process(classesInWorkbook, bfw);
            osw.close();
            statusCode.setMessage(String.valueOf(ReturnCode.valueOf(ReturnCode.CONVERTED.name())));

        } catch (IOException | TemplateException e) {
            LOGGER.error(e.getMessage());
            statusCode.setMessage(e.getMessage());
        }

        return statusCode;
    }
}
